import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
  Row, Col, Card, Form, Input, Icon, Button, DatePicker,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import styles from './operation.less';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

/**
 * 操作日志
 * 使用dva，调用model的effects
 */
/* eslint react/no-multi-comp:0 */
@connect(({ log, loading }) => ({
  log,
  loading: loading,
}))
@Form.create()
class LogOperation extends PureComponent {
  state = {
    expandForm: false,// 简单/复杂查询条件表单切换boolean
    formValues: {},// 查询条件
  };

  columns = [
    {
      title: '序号',
      dataIndex: 'no',
      render: (text, record, index) => <span>{index + 1}</span>,
    },
    {
      title: '日志ID',
      dataIndex: 'id',
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '操作时间',
      dataIndex: 'operated',
      sorter: true,
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      dataIndex: 'action',
    },
    {
      title: '对象',
      dataIndex: 'object',
    },
    {
      title: '操作内容',
      dataIndex: 'operation',
      width: '320px',
      render: (text, record) => (
        <div style={{ wordWrap: 'break-word', wordBreak: 'break-all' }}>
          {text}
        </div>
      ),
    },
    {
      title: 'IP',
      dataIndex: 'ip',
    },
    {
      title: '位置',
      dataIndex: 'location',
    },
    {
      title: '终端',
      dataIndex: 'terminal',
    },
    {
      title: '平台',
      dataIndex: 'platform',
    },
  ];

  // 生命周期方法：组件渲染完成
  componentDidMount() {
    const { dispatch } = this.props;
    // 列表数据获取（默认无条件）
    dispatch({
      type: 'log/fetchLogOperation',
    });
  }

  // Table onChange事件：分页、筛选、排序处理
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'log/fetchLogOperation',
      payload: params,
    });
  };

  // 重置查询条件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'log/fetchLogOperation',
      payload: {},
    });
  };

  // 展开/收起复杂查询条件表单
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  // 查询事件处理
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        // 按天选择的日期，设置一下时分秒，准确比较大小
        operatedSt:
          fieldsValue.operated &&
          fieldsValue.operated[0] &&
          fieldsValue.operated[0].set({ hour: 0, minute: 0, second: 0, millisecond: 0 }).valueOf(),
        operatedEd:
          fieldsValue.operated &&
          fieldsValue.operated[1] &&
          fieldsValue.operated[1]
            .set({ hour: 23, minute: 59, second: 59, millisecond: 999 })
            .valueOf(),
      };
      // 日期控件获取的值是一个moment对象，GET时会出错，需处理
      if (values.operated) delete values.operated;

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'log/fetchLogOperation',
        payload: values,
      });
    });
  };

  // 重新查询
  tableReload = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'log/fetchLogOperation',
      payload: formValues,
    });
  };

  // 查询条件表单 - 简单
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label={<FormattedMessage id="log.form.label.username" />}>
              {getFieldDecorator('username')(<Input placeholder={formatMessage({ id: 'log.form.placeholder.input.please' })} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label={<FormattedMessage id="log.form.label.operated" />}>
              {getFieldDecorator('operated')(
                <RangePicker
                  style={{ width: '100%' }}
                  placeholder={[
                    formatMessage({ id: 'log.form.placeholder.date.start' }),
                    formatMessage({ id: 'log.form.placeholder.date.end' }),
                  ]}
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit"><FormattedMessage id="log.form.btn.query" /></Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}><FormattedMessage id="log.form.btn.reset" /></Button>
              <Button type="link" onClick={this.toggleForm} size='small'><FormattedMessage id="log.form.btn.unfold" /><Icon type="down" /></Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  // 查询条件表单 - 复杂
  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label={<FormattedMessage id="log.form.label.username" />}>
              {getFieldDecorator('username')(<Input placeholder={formatMessage({ id: 'log.form.placeholder.input.please' })} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label={<FormattedMessage id="log.form.label.operated" />}>
              {getFieldDecorator('operated')(
                <RangePicker
                  style={{ width: '100%' }}
                  placeholder={[
                    formatMessage({ id: 'log.form.placeholder.date.start' }),
                    formatMessage({ id: 'log.form.placeholder.date.end' }),
                  ]}
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit"><FormattedMessage id="log.form.btn.query" /></Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}><FormattedMessage id="log.form.btn.reset" /></Button>
              <Button type="link" onClick={this.toggleForm} size='small'><FormattedMessage id="log.form.btn.fold" /><Icon type="up" /></Button>
            </span>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label={<FormattedMessage id="log.form.label.action" />}>
              {getFieldDecorator('action')(<Input placeholder={formatMessage({ id: 'log.form.placeholder.input.please' })} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label={<FormattedMessage id="log.form.label.object" />}>
              {getFieldDecorator('object')(<Input placeholder={formatMessage({ id: 'log.form.placeholder.input.please' })} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
        </Row>
      </Form>
    );
  }

  // 展开/收起 扩展查询条件表单
  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  // 查询列表 默认渲染
  render() {
    const {
      log: { dataLogOperation },
      loading,
    } = this.props;

    return (
      <Fragment>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              rowKey={record => record.id}
              isRowSelect={false}
              loading={loading.effects['log/fetchLogOperation']}
              data={dataLogOperation}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </Fragment>
    );
  }
}

export default LogOperation;
